﻿using System;

using System.Collections.Generic;
using System.Configuration;
using System.IO;

namespace DusonFramework.Core
{
    /// <summary>
    /// Summary description for PublicMethod
    /// </summary>
    public static class VideoHelper
    {
        private static List<string> GetFfmpegTypes()
        {
            return new List<string>() { "asf", "avi", "mpg", "3gp", "mov" };
        }
        private static List<string> GetMencoderTypes()
        {
            return new List<string>() { "wmv", "rm", "rmvb" };
        }
        private static string FfmpegTool = ConfigurationManager.AppSettings["FfmpegTool"];
        private static string MencoderTool = ConfigurationManager.AppSettings["MencoderTool"];
        private static string MplayerTool = ConfigurationManager.AppSettings["MplayerTool"];
        private static string ImageSize = ConfigurationManager.AppSettings["ImageSize"];
        private static string FlvWidth = ConfigurationManager.AppSettings["FrameWidth"];
        private static string FlvHeight = ConfigurationManager.AppSettings["FrameHeight"];

        public static string GetVideoUploadDirectory(string userName)
        {
            return string.Format("~/Users/{0}/Videos/Upload/", userName);
        }
        public static string GetVideoImageDirectory(string userName)
        {
            return string.Format("~/Users/{0}/Videos/Image/", userName);
        }
        public static string GetVideoPlayDirectory(string userName)
        {
            return string.Format("~/Users/{0}/Videos/Play/", userName);
        }
        public static void ConvertVideo(string sourceFile, string targetFile, string imageFile)
        {
            string fileExtension = Path.GetExtension(sourceFile).ToLower();
            if (fileExtension == ".flv")
            {
                //copy directly
                File.Copy(sourceFile, targetFile);
            }
            string toolName = VideoHelper.GetToolName(fileExtension);
            if (toolName == "ffmpeg")
            {
                ConvertVideoByFfmpeg(sourceFile, targetFile, imageFile);
            }
            else if (toolName == "mencoder")
            {
                ConvertVideoByMencoder(sourceFile, targetFile, imageFile);
            }
            CatchVideoImage(targetFile, imageFile);
        }

        private static void ConvertVideoByFfmpeg(string sourceFile, string targetFile, string imageFile)
        {
            string ffmpeg = FfmpegTool;
            if (!File.Exists(ffmpeg) || !File.Exists(sourceFile)) return;
            System.Diagnostics.ProcessStartInfo FilestartInfo = new System.Diagnostics.ProcessStartInfo(ffmpeg);
            FilestartInfo.UseShellExecute = false;
            FilestartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
            FilestartInfo.Arguments = " -i " + sourceFile + " -ab 56 -ar 22050 -b 500 -r 15 -s " + FlvWidth + "x" + FlvHeight + " " + targetFile;
            try
            {
                System.Diagnostics.Process.Start(FilestartInfo);
            }
            catch (Exception ex)
            {
                // log the error here
            }
        }
        private static void ConvertVideoByMencoder(string sourceFile, string targetFile, string imageFile)
        {
            string tool = MencoderTool;
            if ((!File.Exists(tool)) || (!File.Exists(sourceFile))) return;
            System.Diagnostics.ProcessStartInfo FilestartInfo = new System.Diagnostics.ProcessStartInfo(tool);
            FilestartInfo.UseShellExecute = false;
            FilestartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
            FilestartInfo.Arguments = " " + sourceFile + " -o " + targetFile + " -of lavf -lavfopts i_certify_that_my_video_stream_does_not_use_b_frames -oac mp3lame -lameopts abr:br=56 -ovc lavc -lavcopts vcodec=flv:vbitrate=200:mbd=2:mv0:trell:v4mv:cbp:last_pred=1:dia=-1:cmp=0:vb_strategy=1 -vf scale=" + FlvWidth + ":" + FlvHeight + " -ofps 12 -srate 22050";
            try
            {
                System.Diagnostics.Process.Start(FilestartInfo);
            }
            catch
            {
                // log error here
            }
        }
        private static void CatchVideoImage(string flvFile, string imageFile)
        {
            string ffmpeg = FfmpegTool;
            System.Diagnostics.ProcessStartInfo ImgstartInfo = new System.Diagnostics.ProcessStartInfo(ffmpeg);
            //ImgstartInfo.UseShellExecute = false;
            ImgstartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
            ImgstartInfo.Arguments = "   -i   " + flvFile + "  -y  -f  image2   -ss 2 -vframes 1  -s   " + ImageSize + "   " + imageFile;
            try
            {
                System.Diagnostics.Process.Start(ImgstartInfo);
            }
            catch
            {
                // log error here
            }
        }
        private static string GetToolName(string fileExtension)
        {
            string retValue = "";
            string ext = fileExtension.Substring(1);
            foreach (string var in GetFfmpegTypes())
            {
                if (var == ext)
                {
                    retValue = "ffmpeg";
                    break;
                }
            }
            if (retValue == "")
            {
                foreach (string var in GetMencoderTypes())
                {
                    if (var == ext)
                    {
                        retValue = "mencoder";
                        break;
                    }
                }
            }
            return retValue;
        }
    }
}
